#!/bin/bash

#menu list
menu(){
	echo "1.backup /var/log/ directory "
	echo "2.tar file "
	echo "3.find file and backup"
	echo "4.exit"
}

#1.backup /var/log/ directory 
back_var(){
	u_dir="/var/log/"
	ti=`date +%F_%H_%M_%S`	
	[ -e /bak/log/ ] && echo "/bak/log/ already exist" || mkdir -pv /bak/log/
	tar zcvf  /bak/log/${ti}.tar.gz $u_dir
	[ $? -eq 0 ] && echo "tar /var/log/ is succes" || echo "tar /var/log/ is failed"
	ls /bak/log/
	f_file=`find /bak/log/ -mtime +7`
	rm -rf ${f_file}
	[ $? -eq 0 ] && echo "already remove before 7 days files "  || echo "no have before 7 days file" 
}

#2.tar file
tar_file(){
	read -p "please input your need backup file:" u_file
	day=`date +%F`	
	[ -e /bak/${day} ] && echo "the /bak/${day} id created" || mkdir /bak/${day}
	tt=`date +%H_%M_%S`
	t_file=`echo ${u_file} |tr -s "/" "\n"|tail -n 1`
	find ${u_file}
	[ $? -eq 0 ] && tar zcvf  /bak/${day}/${t_file}.${tt}.tar.gz ${u_file} || echo "no such file"		
	ls /bak/$day
}

#3.find file and backup 
find_file(){
	echo -e "find range\e[31m(1.name,2.size,3.type,4.mtime,5.user,6.group)\e[0m"
	read -p "input file directory range example(/etc/):" u_dire
	read -p "input file name format(-name filename):" u_fname
	read -p "input file size format(-size filesize):" u_fsize
	read -p "input file type format(-type filetype):" u_ftype
	read -p "input file mtime format(-mtime filemtine):" u_fmtime
	read -p "input file user format(-user fileuser):" u_fuser
	read -p "input file group format(-group filegroup):" u_fgroup

	[ -d /bak/find/ ] && echo "the /bak/find/ has create" || mkdir /bak/finds
	c_fl=`find ${u_dire} ${u_fname} ${u_fsize} ${u_ftype} ${u_fmtime} ${u_user} ${u_fgroup} -print`
	if (( $? == 0 ));then
		echo $c_fl
		read -p "do you need bakup [y/n]:" u_cho
		if (( $u_cho == y ));then
		tim=`date +%F_%H_%M_%S`
		the_file=`echo ${c_fl} |tr -s "/" "\n"|tail -n 1`
		tar zcvf /bak/finds/${the_file}.${tim}.tar.gz ${c_fl}
		else 
		echo "not backup for this fing "
		fi	
	fi
}

#main function
main(){
	while :
	do
	clear
	menu
	read -p "please input you option:" u_opt
	case $u_opt in
	1)
	back_var
	;;
	2)
	tar_file
	;;
	3)
	find_file
	;;
	4)
	exit
	;;
	*)
	exit
	;;
	esac
	read
	done
}
main
